<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class MemberCoupon extends Model
{
    use HasFactory;
    use SoftDeletes;
    protected $fillable = [
        "member_id",
        "red_id",
        "coupon_id",
        "indate",
        "status"
    ];

    /**
     * 设置卡券有效期
     * @param $_value
     * @param $_data
     * @return int
     */
    public function setIndateAttribute($_value)
    {
        $_time = 1;
        $_coupon = Coupons::where("id",$_value["coupon_id"])
            ->select(array("time_type","time"))
            ->first();
        if($_coupon["time_type"] == 1) {
            // 永久有效
            $_time = 1;
        } else if($_coupon["time_type"] == 2) {
            // 过期时间，有效期至
            $_time = $_coupon["time"];
        } else {
            $_time = time() + 86400 * $_coupon["time"];
        }
        $this->attributes['indate'] = $_time;
    }

    /**
     * 卡券信息
     * @return mixed
     */
    public function getCouponAttribute()
    {
        $Coupon = Coupons::where("id",$this->coupon_id)
            ->select("name","cover","type","type_value","time_type","time","detail","address")
            ->first();
        $Coupon->past = false;
        if($this->indate != 1) {
            if($this->indate + 86400-1 < time()) {
                $Coupon->past = true;
            }
        }
        return $Coupon;
    }
}
